#include "led_dev.h"
#include "app_easy_timer.h"
#include "global_cfg.h"
#include "task_app.h"

#define printf ;
void led_init()
{
    GPIO_ConfigurePin(LED_R_PORT, LED_R_PIN, OUTPUT, PID_GPIO, false);
    GPIO_SetInactive(LED_R_PORT, LED_R_PIN);

    GPIO_ConfigurePin(LED_G_PORT, LED_G_PIN, OUTPUT, PID_GPIO, false);
    GPIO_SetInactive(LED_G_PORT, LED_G_PIN);
}

uint8_t led_status = 0;

led_loop led_loop_array[] =
{
    {4, { {1, 50}, {0, 50}, {1, 50}, {0, 50} }},    //slow_flash	used for button
    {4, { {1, 10}, {0, 20}, {1, 10}, {0, 20} }},    //fast_flash  used for upgrade
    {4, { {1, 5}, {0, 10}, {1, 15}, {0, 20} }},			//
};

led_loop cb_led_loop;
uint16_t cb_loop_num = 0;
uint8_t led_color = 0;
timer_hnd cd_led_timer = EASY_TIMER_INVALID_TIMER;
int i = 0;

void led_cb()
{
    cd_led_timer = EASY_TIMER_INVALID_TIMER;
    if (i >= cb_led_loop.count)
    {
        i = 0;
        --cb_loop_num;
        if (cb_loop_num <= 0)
        {
            LED_G_OFF() ;
						LED_R_OFF();
            return;
        }
    }
    if (1 == cb_led_loop.effect[i].status)
    {
        is_conn() ? LED_G_ON() : LED_R_ON();
        if (++i < cb_led_loop.count || cb_loop_num > 0)
        {
            cd_led_timer = app_easy_timer(cb_led_loop.effect[i - 1].interval_time, led_cb);
        }
    }
    else
    {
        LED_G_OFF() ;
				LED_R_OFF();
        if (++i < cb_led_loop.count || cb_loop_num > 0)
        {
            cd_led_timer = app_easy_timer(cb_led_loop.effect[i - 1].interval_time, led_cb);
        }
    }
}

void led_start(uint8_t select, uint16_t loop_num)
{
    if (select > sizeof(led_loop_array) / sizeof(led_loop) - 1)
    {
        printf("select error\n");
        return ;
    }
    if (0 != led_loop_array[select].count)
    {
        if (cd_led_timer != EASY_TIMER_INVALID_TIMER)
        {
            app_easy_timer_cancel(cd_led_timer);
            cd_led_timer = EASY_TIMER_INVALID_TIMER;
        }
        i = 0;
        cb_loop_num = loop_num;
        cb_led_loop = led_loop_array[select];
        led_cb();
    }
}

//void led_run(uint8_t select,uint16_t loop_num){
//  if(select>sizeof(led_loop_array)/sizeof(led_loop)-1){
//      printf("select error\n");
//      return ;
//  }
//  led_start(led_loop_array[select],loop_num);
//}
uint8_t led_flag = 0;
void led_task(uint8_t mode, uint16_t loop)
{
    uint8_t tmp[3];
    //sscanf(buf,"led_run%d %ld",&mode,&loop);
    tmp[0] = mode;
    tmp[1] = (uint8_t)(loop >> 8);
    tmp[2] = (uint8_t)(loop);
    //led_color=sel_color;
//  if(led_flag==0){
    send_task_msg(LED_RUN, tmp, 3);
//  }
}
